const express = require('express');
const router = express.Router();
const OrderController = require('../controllers/orderController');
const { authenticateToken, requireAdmin } = require('../middleware/auth');
const { authenticateClientToken } = require('../middleware/clientAuth');
const { body } = require('express-validator');
const { handleValidationErrors } = require('../middleware/validation');

// 创建订单验证规则
const validateCreateOrder = [
  body('order_number')
    .optional()
    .isString()
    .isLength({ min: 3, max: 50 })
    .withMessage('订单号长度必须在3-50个字符之间'),
  body('order_type')
    .isIn(['dine_in', 'takeaway', 'reservation_dine_in', 'reservation_takeaway', 'delivery'])
    .withMessage('订单类型必须是 dine_in, takeaway, reservation_dine_in, reservation_takeaway 或 delivery'),
  body('table_number')
    .optional()
    .isInt({ min: 1 })
    .withMessage('桌号必须是正整数'),
  body('delivery_address')
    .if(body('order_type').equals('delivery'))
    .notEmpty()
    .withMessage('外卖订单必须提供配送地址')
    .isLength({ max: 500 })
    .withMessage('配送地址不能超过500个字符'),
  body('delivery_phone')
    .if(body('order_type').equals('delivery'))
    .notEmpty()
    .withMessage('外卖订单必须提供配送电话')
    .matches(/^[1-9]\d{7,10}$/)
    .withMessage('配送电话格式不正确'),
  body('delivery_notes')
    .optional()
    .isLength({ max: 500 })
    .withMessage('配送备注不能超过500个字符'),
  body('payment_method')
    .isIn(['cash', 'card', 'alipay', 'wechat', 'apple_pay', 'google_pay'])
    .withMessage('支付方式不正确'),
  body('notes')
    .optional()
    .isLength({ max: 500 })
    .withMessage('订单备注不能超过500个字符'),
  body('items')
    .isArray({ min: 1 })
    .withMessage('订单项不能为空'),
  body('items.*.menu_item_id')
    .isInt({ min: 1 })
    .withMessage('菜品ID必须是正整数'),
  body('items.*.quantity')
    .isInt({ min: 1 })
    .withMessage('数量必须是正整数'),
  body('items.*.notes')
    .optional()
    .isLength({ max: 200 })
    .withMessage('菜品备注不能超过200个字符'),
  body('coupon_code')
    .optional()
    .isLength({ min: 3, max: 50 })
    .withMessage('优惠券代码长度必须在3-50个字符之间'),
  handleValidationErrors
];

// 更新订单状态验证规则
const validateUpdateStatus = [
  body('status')
    .isIn(['pending', 'confirmed', 'preparing', 'ready', 'completed', 'cancelled'])
    .withMessage('订单状态不正确'),
  body('estimated_time')
    .optional()
    .isInt({ min: 1 })
    .withMessage('预计时间必须是正整数（分钟）'),
  handleValidationErrors
];

// 更新支付状态验证规则
const validateUpdatePayment = [
  body('payment_status')
    .isIn(['pending', 'processing', 'completed', 'failed', 'refunded'])
    .withMessage('支付状态不正确'),
  body('payment_id')
    .optional()
    .isLength({ max: 100 })
    .withMessage('支付ID不能超过100个字符'),
  handleValidationErrors
];

// 公共路由（不需要认证）
router.post('/', validateCreateOrder, OrderController.createOrder);

// 订单状态更新路由 - 支持管理员和客户端认证（需要在全局认证之前）
router.put('/:id/status', (req, res, next) => {
  console.log('🔄 订单状态更新请求:', req.params.id, req.body);
  console.log('🔑 Authorization头:', req.headers.authorization);
  
  // 先尝试客户端认证
  authenticateClientToken(req, res, (err) => {
    if (!err && req.user) {
      console.log('✅ 客户端认证成功:', req.user);
      // 客户端认证成功，继续处理
      return next();
    }
    console.log('❌ 客户端认证失败，尝试管理员认证');
    // 客户端认证失败，尝试管理员认证
    authenticateToken(req, res, (err) => {
      if (!err && req.user) {
        console.log('✅ 管理员认证成功');
        return requireAdmin(req, res, next);
      }
      console.log('❌ 两种认证都失败');
      // 两种认证都失败
      return res.status(401).json({
        success: false,
        message: '需要管理员权限或有效的客户端令牌',
        error_code: 'AUTH_REQUIRED'
      });
    });
  });
}, validateUpdateStatus, OrderController.updateOrderStatus);

// 需要认证的路由
router.use(authenticateToken);

// 用户订单路由
router.get('/my-orders', OrderController.getUserOrders);
router.get('/my-orders/:id', OrderController.getOrderDetail);
router.get('/order-number/:orderNumber', OrderController.getOrderByNumber);
router.put('/:id/cancel', OrderController.cancelOrder);
router.get('/statistics/my', OrderController.getOrderStatistics);

// 管理员路由
router.get('/admin/all', requireAdmin, OrderController.getAllOrders);
router.put('/:id/payment', requireAdmin, validateUpdatePayment, OrderController.updatePaymentStatus);
router.get('/statistics/admin', requireAdmin, OrderController.getOrderStatistics);
router.get('/popular-items', requireAdmin, OrderController.getPopularItems);
router.get('/stats', requireAdmin, OrderController.getOrderStatistics);
router.get('/trends', requireAdmin, OrderController.getOrderTypeTrend);
router.get('/categories', requireAdmin, OrderController.getCategorySales);
router.get('/top-customers', requireAdmin, OrderController.getTopCustomers);
router.get('/type-distribution', requireAdmin, OrderController.getOrderTypeDistribution);
router.get('/payment-distribution', requireAdmin, OrderController.getPaymentMethodDistribution);
router.get('/payment-trend', requireAdmin, OrderController.getPaymentMethodTrend);



// 通用路由（用户和管理员都可访问）
router.get('/:id', OrderController.getOrderDetail);

module.exports = router;